// pages/payfor/index.js
var PayTotalPrice = 0;
var OrderTicketID = 1213;
var order = "";
var coupons = "";
var ticketprice = 0;
var reqPaySign = '';
var reqSaveOrderSign = '';
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var app = getApp();
var strAppCode = config.SmallApp;
var lingshilist = "";
var id = "";
var detail = "";
var code = "";
var finalMoney = "";
var Money = "";
var finalyuanMoney = "";
var cardlist = [];
var paymoney = "";
var yuanMoney = "";
var paymethod = "";
var chooseseat = "";
var plandate = '';
var buyitem = "";
var imgpath = config.imgHost;
var tempimg = "";
/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var total_micro_second = 5 * 60 * 1000;

/* 毫秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止",
      issuccess: false,
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that);
  }
    , 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return min + "分" + sec + "秒";
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clock: '',//支付剩余时间
    year: '',//当前的年份
    chkzuolist: [],//选择的座位
    chkzuo: '',//选择的座位
    payforprice: 0,//付钱价格
    piaoprice: 0,//票价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    chkday: '',//日期
    changciid: '',//场次id
    time: '',//开场时间
    lingshilist: [],//零食列表
    zhifuqian: 0,//支付的钱
    open: false,//列表选项
    items: [],
    imgpath: imgpath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    tempimg = JSON.parse(options.detail);
    this.setData({ tempimg })
    plandate = JSON.parse(options.plandate)
    console.log(plandate)
    id = options.EventId;
    buyitem = options.buyitem;
    console.log(buyitem)
    this.setData({ buyitem })
    chooseseat = JSON.parse(options.chooseseat);
    for (var i = 0; i < chooseseat.length; i++) {
      chooseseat[i].Seattext = chooseseat[i].Seattext.split("-")[0] + "排" + chooseseat[i].Seattext.split("-")[1] + '座'
    }
    var chooseseatlength = chooseseat.length;
    console.log(chooseseat)
    order = JSON.parse(options.order);
    console.log(order)
    paymoney = options.paymoney;
    this.setData({ paymoney, chooseseat, chooseseatlength, plandate })
    var that = this;
    if (app.globalData.hasLogin) { //TODO记得修改
      //TODO获取电影详情
      return req.ActivityFilmDetail(id).then(res => {
        console.log(res)
        if (res.data.success) {
          detail = res.data.data;
          detail.EventEnd = detail.EventEnd.split("T")[0];
          detail.EventStart = detail.EventStart.split("T")[0]
          var time = detail.ResponseTime.split("T")[1].split(".")[0]
          detail.ResponseTime = detail.ResponseTime.split("T")[0]

          console.log(detail)
          Money = finalMoney = paymoney;
          finalyuanMoney = yuanMoney = finalMoney + detail.EventDiscountValue;
        }
        that.setData({ detail, finalMoney, finalyuanMoney, phone: app.globalData.loginuserinfo.mobile, time })
        wx.setNavigationBarTitle({
          title: detail.EventDescForMobi,
        })
      }).then(() => {
        return req.CardList(app.globalData.token).then(res => {

          cardlist = res.data.data;
          console.log(cardlist);
          if (cardlist.length > 0) {
            this.setData({ hascard: true })
            paymethod = 0;
            for (var i = 0; i < cardlist.length; i++) {
              cardlist[i].cardNostart = cardlist[i].Mcode.substring(0, 4) + "****" + cardlist[i].Mcode.substr(cardlist[i].Mcode.length - 2, cardlist[i].Mcode.length)
            }
          }
          that.setData({ cardlist: cardlist })
        })
      }).then(() => {
 
        if (cardlist.length > 0) {
          return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale, detail.EventDiscountThreshold).then(res => {
            paymoney = res.data.pricetotal
            that.setData({ paymoney })
          })
        } else {
          return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale_wx, detail.EventDiscountThreshold).then(res => {
            paymoney = res.data.pricetotal
            this.setData({ paymoney })
          })
        }
      })
    } else {
      wx.login({
        success: function (res) {
          console.log(res)
          code = res.code;
          return req.MiniAppLogin(code).then(res => {
            if (res.data.notRegister) {//TODO记得修改
              wx.reLaunch({
                url: '../regiest/regiest?fromhuodongmovie=true&&EventId=' + id + ''
              })
            } else {

              var token = res.data.data
              //TODO请求用户信息
              app.globalData.hasLogin = true;
              app.globalData.token = token;
              return req.GetUserInfo(token).then(res => {
                if (res.data.success) {

                  app.globalData.loginuserinfo = res.data.data // res.data.data
                  that.setData({ detail, phone: app.globalData.loginuserinfo.mobile, hasLogin: true })
                  console.log(app.globalData.loginuserinfo)
                  that.setData({ hasF: true })
                  wx.getUserInfo({
                    success: function (res) {
                      app.globalData.userinfo = res.userInfo
                      console.log(res)
                      that.setData({ detail, finalMoney, phone: app.globalData.loginuserinfo.mobile })
                    }, fail: function () {
                      //拒绝授权
                    },
                  })

                } else {
                  wx.showModal({
                    title: '提示',
                    content: '登陆失败,请检查网络',
                  })
                }
              }).then(() => {
                return req.ActivityFilmDetail(id).then(res => {

                  if (res.data.success) {
                    detail = res.data.data;
                    detail.EventEnd = detail.EventEnd.split("T")[0];
                    detail.EventStart = detail.EventStart.split("T")[0]
                    console.log(detail)
                    Money = finalMoney = paymoney;
                    finalyuanMoney = yuanMoney = finalMoney + detail.EventDiscountValue;
                  }
                  that.setData({ detail, finalMoney, finalyuanMoney, phone: app.globalData.mobile })
                  wx.setNavigationBarTitle({
                    title: detail.EventDescForMobi,
                  })
                }).then(() => {
                  return req.CardList(app.globalData.token).then(res => {

                    cardlist = res.data.data;
                    console.log(cardlist);
                    if (cardlist.length > 0) {
                      for (var i = 0; i < cardlist.length; i++) {
                        cardlist[i].cardNostart = cardlist[i].Mcode.substring(0, 4) + "****" + cardlist[i].Mcode.substr(cardlist[i].Mcode.length - 2, cardlist[i].Mcode.length)
                      }
                    }
                    that.setData({ cardlist: cardlist })
                  }).then(() => {
                
                    if (cardlist.length > 0) {
                      return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale, detail.EventDiscountThreshold).then(res => {
                        paymoney = res.data.pricetotal
                        that.setData({ paymoney })
                      })
                    } else {
                      return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale_wx, detail.EventDiscountThreshold).then(res => {
                        paymoney = res.data.pricetotal
                        this.setData({ paymoney })
                      })
                    }

                  })
                })
              })
            }
          })
        }, fail: function (res) {
          wx.showModal({
            title: '提示',
            content: '登陆失败',
          })
        }
      })
    }


    //计时器

    //TODO支付


    //结束标识符
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  showitem: function () {
    this.setData({
      open: !this.data.open
    })
  },
  showitem2: function () {
    this.setData({
      open2: !this.data.open
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  radioChange: function (e) {
    console.log(e)
    paymethod = e.detail.value;
    if (paymethod === '') {

    }
    if (paymethod == 'wxpay') {
      return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale_wx, detail.EventDiscountThreshold).then(res => {
        paymoney = res.data.pricetotal
        this.setData({ paymoney })
      })
    } else {
      return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, chooseseat.length, plandate.PriceSale, detail.EventDiscountThreshold).then(res => {
        paymoney = res.data.pricetotal
        this.setData({ paymoney })
      })
    }
  },

  moviebill: function () {
    wx.navigateTo({
      url: '../huodong/moviebill',
    })
  },

  paynow: function () {
    // OrderGoodsDetailID = "";
    // for (var i = 0; i < payresult.taborder.length; i++) {
    //   if (i == payresult.taborder.length - 1) {
    //     OrderGoodsDetailID = OrderGoodsDetailID + payresult.taborder[i].OrderGoodsDetailID + ''
    //   } else {
    //     OrderGoodsDetailID = OrderGoodsDetailID + payresult.taborder[i].OrderGoodsDetailID + ","
    //   }

    // }

    if (paymethod === '') {
      wx.showModal({
        title: '提示',
        content: '请选择支付方式',
      })
    } else if (paymethod == 'wxpay') {
      //TODO 微信支付
      // orderTicketID, OrderGoodsDetailID,
      // LinkTelcode, coupons, PayTotalPrice, sign, token
      console.log('微信支付');


      return req.GetMiniFlimAppPaySign(order[0].OrderTicketID, paymoney, "", app.globalData.token).then(res => {

        console.log(res)
        var pay = res.data
        //发起支付   
        var timeStamp = pay.TimeStamp;
        console.log("timeStamp:" + timeStamp)
        var packages = pay.Package;
        console.log("package:" + packages)
        var nonceStr = pay.NonceStr;
        console.log("nonceStr:" + nonceStr)
        var paySign = pay.PaySign;
        console.log("paySign:" + paySign)
        var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
        //调用支付
        // pay(param)
        console.log("支付")
        wx.requestPayment({
          timeStamp: param.timeStamp,
          nonceStr: param.nonceStr,
          package: param.package,
          signType: param.signType,
          paySign: param.paySign,
          success: function (res) {
            // 业务逻辑
            console.log("支付成功")
            wx.showToast({
              title: '支付成功',
              success: function () {
                setTimeout(function () {
                  // 放在最后--
                  wx.reLaunch({
                    url: '../member/buyTicketsOrder',
                  })
                }
                  , 3000)


              }
            })

            //TODO 购买成功 跳转到 订单
            // wx.redirectTo({
            //   url: '../payfor/detail?PayTotalPrice=' + PayTotalPrice + '&&order=' + JSON.stringify(order) + '&&coupons=' + coupons + '' + ticketprice + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + ticketprice + '&&lingshilist=' + JSON.stringify(lingshilist)
            // })

          }, fail: function (error) {
            console.log(error)

          }
        })
      })
    }
    else {  //TODO 会员卡支付
      console.log(cardlist)
      console.log('会员支付');
      if (paymoney > cardlist[paymethod].Balance) {
        wx.showModal({
          title: '提示',
          content: '卡内余额不足',
        })
        wx.hideLoading();
        return false;
      }
      wx.showLoading({
        title: '购票中',
      })
      // strCardNo = cardlist[paymethod].Mcode;
      // var paysign = "OrderTicketID=" + payresult.tab[0].OrderTicketID + "OrderGoodsDetailID=" + OrderGoodsDetailID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "coupons=" + coupons + "" + "PayTotalPrice=" + (detail.PriceSale) * (detail.buynum);
      // return req.GetSignStr(paysign).then(res => {
      //   if (res.data.success) {
      //     ActivityGoodsOrderCardSign = res.data.data;
      //   }
      // }).then(() => {

      return req.ActivFilmOrdB(order[0].OrderTicketID, "123", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile, "", paymoney, app.globalData.token).then(res => {
        console.log(res)
        var result = res.data.data
        // if (res.data.success) {
        //跳转到支付成功页面
        if (res.data.success) {
          wx.showToast({
            title: '支付成功',
            success: function () {
              setTimeout(function () {
                // 放在最后--
                wx.reLaunch({
                  url: '../member/buyTicketsOrder',
                })
              }
                , 3000)


            }
          })
          //TODO 支付成功 跳转订单页面
          // wx.redirectTo({
          //   url: '../payfor/detail?PayTotalPrice=' + PayTotalPrice + '&&order=' + JSON.stringify(order) + '&&coupons=' + coupons + '' + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + ticketprice + '&&lingshilist=' + JSON.stringify(lingshilist) + '&&result=' + JSON.stringify(result)
          // })
        } else {
          wx.showModal({
            title: '提示',
            content: '会员卡支付失败',
          })
          setTimeout(function () {
            // 放在最后--
            wx.hideLoading();
          }
            , 1600)
          return false;
        }

      })

    }
  },
  godetail: function () {
    wx.redirectTo({
      url: '../payfor/detail?PayTotalPrice=' + paymoney + '&&order=' + JSON.stringify(order) + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&result=' + JSON.stringify(result)
    })
  }
})